import {
	ignoreHtml,
	getUrl,
	errorModal
} from '@/static/js/common.js';
import {
	hasValue
} from '@/static/js/formUtil.js';

export const om = {
	toast: function(text, duration, success) {
		if (!text) {
			return
		}
		uni.showToast({
			title: ignoreHtml(text),
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	getAvatar(code) {
		//#ifdef APP-PLUS
		if (!code) {
			return (store.state.sexCode && store.state.sexCode === '23593') ?
				(store.state.avatar ||
					''
				) :
				(store.state.avatar ||
					''
				)
		} else {
			return (code && code === '23593') ?
				(store.state.avatar ||
					''
				) :
				(store.state.avatar ||
					''
				)
		}
		//#endif

		//#ifndef APP-PLUS
		if (!code) {
			return (store.state.sexCode && store.state.sexCode === '23593') ?
				(store.state.avatar || 'static/images/menus/girl.png') :
				(store.state.avatar || 'static/images/menus/boy.png')
		} else {
			return (code && code === '23593') ?
				(store.state.avatar || 'static/images/menus/girl.png') :
				(store.state.avatar || 'static/images/menus/boy.png')
		}

		//#endif
	},
	//获取打开文件的静态路径
	getFilePath:function(path){//path:文件的相对路径
		if (!path) {
			return ""
		}
		let requestUrl = path
		if (requestUrl.slice(0, 4) !== 'http') {
			if (!getApp().globalData.url) {
				if (service.getAppType() == "app") {
					uni.reLaunch({
						url: "/pages/login/login/login"
					})
				} else {
					om.toast("服务器网址为空！");
					return
				}
			} else {
				 requestUrl = getApp().globalData.url + store.state.subUrl + requestUrl;
			 }
		}
		return requestUrl
	},
	getUrl: function(url) {
		if (!url) {
			return ""
		}
		let requestUrl = url
		if (requestUrl.slice(0, 4) !== 'http') {
			if (!getApp().globalData.url) {
				if (service.getAppType() == "app") {
					uni.reLaunch({
						url: "/pages/login/login/login"
					})
				} else {
					om.toast("服务器网址为空！");
					return
				}
			} else {
				
				requestUrl = getApp().globalData.url + store.state.subUrl + requestUrl;
				
				// //#ifndef APP-PLUS
				//requestUrl = "/sk/" + requestUrl;
				////#endif
			 }
		}
		if (!~requestUrl.indexOf(".do")) {
			requestUrl += ".do"
		}
		return requestUrl
	},
	request: function(url, postData, method, hideLoading, attr = {}) {
		attr.url = om.getUrl(url);
		attr.method = method;

		attr.data = {
			loginType: service.getAppType(),
			loginUserId: store.state.userId
		}

		if (postData && typeof(postData) === "object") {
			attr.data = Object.assign({}, attr.data, postData);
		}
		if (!attr.header) {
			attr.header = {}
		}
		if (!attr.header['Content-Type']) {
			attr.header['Content-Type'] = 'application/x-www-form-urlencoded';
		}
		let token = store.state.token;
		if (token) {
			attr.header["Authorization"] = token;
		}
		attr.withCredentials =  true
		attr.crossDomain = true
		attr.method = attr.method || "get"
		attr.dataType = "json"
		//接口请求
		if (!hideLoading) {
			uni.showLoading({
				mask: true,
				title: '请稍候...'
			})
		}
		return new Promise((resolve, reject) => {
			attr.success = (res) => {
				!hideLoading && uni.hideLoading()
				if (!res.data.succeed && res.data.msg && res.data.msg == "在线状态异常，请尝试重新登录！") {
					store.commit("setHasLogin", false)
				}
				resolve(res.data)
			};
			attr.fail = (err) => {
				if (!hideLoading) {
					om.toast("网络不给力，请稍后再试~")
				}
				reject(err)
			};
			uni.request(attr)
		})
	},
	mateRequest: function(url, postData, method, hideLoading) {
		let attr = {
			url: getApp().globalData.omMateServer + url,
			method: method
		}
		attr.data = {
			loginType: service.getAppType(),
			loginUserId: store.state.userId
		}

		if (postData && typeof(postData) === "object") {
			attr.data = Object.assign({}, attr.data, postData);
		}
		if (!attr.header) {
			attr.header = {}
		}
		if (!attr.header['Content-Type']) {
			attr.header['Content-Type'] = 'application/json';
		}
		attr.method = attr.method || "get"
		attr.dataType = "json"
		//接口请求
		if (!hideLoading) {
			uni.showLoading({
				mask: true,
				title: '请稍候...'
			})
		}

		return new Promise((resolve, reject) => {
			attr.success = (res) => {
				!hideLoading && uni.hideLoading()
				if (!res.data.success) {
					om.toast(res.data.message)
				}
				resolve(res.data)
			};
			attr.fail = (err) => {
				if (!hideLoading) {
					om.toast("网络不给力，请稍后再试~")
				}
				reject(err)
			};
			uni.request(attr)
		})

	},
	// 显示页面数据
	getPageInfo(show, title, params, id) {
		uni.setStorage({
			key: 'info',
			data: show,
		})
		let itemId = ''
		if (id) {
			itemId = id
		}
		var url = '/pages/public/cache-info/cache-info?cacheKey=info&title=' + title + '&itemId=' + itemId
		if (params) {
			url = getUrl(url, params)
		}
		uni.navigateTo({
			url: url
		})
	},
	// 显示页面数据
	getPageInfoByUrl(durl, title) {
		uni.navigateTo({
			url: '/pages/public/cache-info/cache-info?durl=' + durl + '&title=' + title,
		})
	},
	// 显示页面数据
	getPageInfoByTableMark(tableMark, id, title) {
		om.request('wxCommon/getColumnInfo', {
			tableMark: tableMark,
			id: id
		}).then(res => {
			if (res.succeed) {
				om.getPageInfo(res.value, title)
			} else {
				om.toast(ignoreHtml(res.msg))
			}
		})
	},
	// 获取表单页面
	getFormInfo(fileId, busCode, isredirect, failFun,index) {
		let param = {
			id: fileId,
			busCode: busCode
		}
		om.request('wxCommon/getInfo', param).then(res => {
			if (res.succeed) {
				uni.setStorageSync(
					'forminfo',
					res.value
				)
				if (busCode != 'PER0504') {
					if (isredirect) {
					uni.redirectTo({
							url: '/pages/public/show/show?formIndex='+index
						})
					} else {
						uni.navigateTo({
							url: '/pages/public/show/show?formIndex='+index
						})
					}
				} else {
					if (isredirect) {
						uni.redirectTo({
							url: '/pages/public/show/showOther'
						})
					} else {
						uni.navigateTo({
							url: '/pages/public/show/showOther'
						})
					}
				}
			} else {
				if (failFun) {
					failFun(res.msg)
				} else {
					if (res.msg) {
						errorModal(null, '提示', res.msg)
					}
				}
			}
		})
	},
	// 获取表单页面
	getFormInfoByFileCode(fileCode, busCode) {
		let param = {
			fileCode: fileCode,
			busCode: busCode
		}
		om.request('wxCommon/getInfoByFileCode', param).then(res => {
			if (res.succeed) {
				uni.setStorage({
					key: 'forminfo',
					data: res.value
				})
				uni.navigateTo({
					url: '/pages/public/show/show'
				})
			}
		})
	},
	formSave(url, formdata, $vm, successFun, failFun) {
		if (!$vm) {
			var pages = getCurrentPages();
			$vm = pages[pages.length - 1];
		}
		//#ifdef APP-PLUS
		if (!$vm.formdata) {
			$vm = $vm.$vm
		}
		//#endif
		if (!hasValue(formdata)) {
			formdata = $vm.formdata
		}
		if ($vm.saveFlag) {
			om.toast('数据正在保存中，请稍后……')
			return
		}
		formdata.zuserId = store.state.userId
		formdata.zuserName = store.state.userName
		if ($vm.busCode) {
			formdata.busCode = $vm.busCode
		}
		$vm.saveFlag = true
		
		
		formdata = Object.keys(formdata)		
		    .filter((key) => formdata[key] !== null && formdata[key] !== undefined)
		    .reduce((acc, key) => ({ ...acc, [key]: formdata[key] }), {});
		
		let lookAuthFieldIdArr = []
		for(let configItem of $vm.$refs.autoform.configData){
			for(let editor of configItem.editors){
				if(editor.type != 'subbox'){
					let subValue = formdata[editor.valueField];
					if (subValue && subValue === "******") {
						lookAuthFieldIdArr.push(editor.formFieldId);
						formdata.delete(editor.valueField);
						if (editor.nameField) {
							formdata.delete(editor.nameField);
						}
					}
				}else{
					let list = JSON.parse(formdata[editor.valueField])
					if(list && list.length){
						list.forEach(e => {
							for (var k in e) {
								if (e[k] === "******") {
									if (e.hasOwnProperty("salaryName") && e.hasOwnProperty("itemId")) {
										lookAuthFieldIdArr.push(e.itemId);
									}else{
										for(let subEditor of $vm.subConfigData[editor.key][0].editors){
											if(subEditor.valueField == k){
												lookAuthFieldIdArr.push(subEditor.formFieldId);
											}
										}	
									}
									delete e[k];
								}
							}
						})
					}
					$vm.$set(formdata,editor.nameField, JSON.stringify(list));
				}
			}
		}
		 if (lookAuthFieldIdArr.length > 0) {
		            $vm.$set(formdata,"lookAuthFieldIds", lookAuthFieldIdArr.filter((e, index) => lookAuthFieldIdArr.indexOf(e) === index).join(","));
		        }	
			
		om.request(url, formdata, 'post').then(res => {
			if (res.succeed) {
				om.toast('保存成功')
				let id = null
				if ($vm.$_.isNumber(res.value)) {
					id = res.value
				} else if ($vm.$_.isPlainObject(res.value)) {
					id = res.value.id
				}
				if (successFun) {
					successFun((formdata.formId || formdata.id) || id)
				} else {
					om.getFormInfo((formdata.formId || formdata.id) || id, $vm.busCode, true);
				}
			} else {
				$vm.saveFlag = false
				if (failFun) {
					failFun(ignoreHtml(res.msg))
				} else {
					om.toast(ignoreHtml(res.msg || '保存失败'), 4000);
				}
			}
		}, err => {
			$vm.saveFlag = false
		});
	},
	openHistoryPage(title, busCode) {
		uni.navigateTo({
			url: '/pages/public/history/history?title=' + (title || '') + '&code=' + busCode
		});
	},
	openPdf: function(item) {
		// debugger
		let busCode = '',
			simpleClazzName = '',
			fileId = '',
			pdfFileUrl = '',
			fileUplaodKey='';
			
		if (item.attr) {
			if (item.attr.busCode)
				busCode = item.attr.busCode
			if (item.attr.simpleClazzName)
				simpleClazzName = item.attr.simpleClazzName
			if (item.attr.fileId)
				fileId = item.attr.fileId
			if (item.attr.pdfFileUrl)
				pdfFileUrl = item.attr.pdfFileUrl
			if(item.fileUplaodKey)
				fileUplaodKey = item.fileUplaodKey
		}
		uni.navigateTo({
			url: "/pages/public/pdf-preview/pdf-preview?busCode=" + busCode + "&fileId=" + fileId +
				"&simpleClazzName=" +
				simpleClazzName + "&pdfFileUrl=" + pdfFileUrl +'&fileUplaodKey='+fileUplaodKey
		})
	},
	uploadFile: function(url, src, files, formData, nameField, hideLoading) {
		const that = this
		if (!hideLoading) {
			uni.showLoading({
				title: '请稍候...'
			})
		}
		var options = {
			name: 'file',
			method: 'get',
			withCredentials: true
		}
		if (url) {
			options.url = om.getUrl(url)
		}
		if (src) {
			options.filePath = src
		}
		if (files) {
			options.files = files
		}
		if (nameField) {
			options.name = nameField
		}
		if (!formData) {
			formData = {}
		}
		formData.loginType = service.getAppType()
		options.formData = formData

		let token = store.state.token;
		if (token) {
			options.header = {
				"Authorization": store.state.token
			}
		}
		return new Promise((resolve, reject) => {
			options.success = function(res) {
				if (!hideLoading) {
					uni.hideLoading()
				}
				resolve(res.data)
			}
			options.fail = function(res) {
				reject(res)
				if (!hideLoading) {
					uni.hideLoading()
				}
				that.toast(res.message);
			}
			const uploadTask = uni.uploadFile(options)
		})
	},
	// 设置登录凭证
	setToken: function(name, pwd, key) {
		let token = {
			name: name,
			pwd: pwd,
			key: key,
			date: new Date()
		}
		uni.setStorageSync("token", JSON.stringify(token))
	},
	// 获取登录凭证
	getToken() {
		let tokenStr = uni.getStorageSync("token")
		if (tokenStr) {
			let token = JSON.parse(tokenStr)
			if ((new Date().getTime() - new Date(token.date).getTime()) < 7 * 24 * 3600 * 1000) {
				return token;
			} else {
				uni.removeStorageSync("token")
				return ""
			}
		} else {
			return ""
		}
	},
	clearToken() {
		uni.removeStorageSync("token")
	},
	getSystemInfoSync(){
		switch(uni.getSystemInfoSync().platform){
			case 'android':
				store.state.platform = 'android'
			   break;
			case 'ios':
			   store.state.platform = 'ios'
			   break;
			case 'devtools':
			   store.state.platform = 'devtools'
			   break;
			default:
			   store.state.platform = 'other'
			   break;
		}
	},
	getBaiduToken(){
		om.request(
			'baiduCloudApi/getAccessToken',
		).then(res=>{
			if(res.succeed){
				try{
					uni.setStorageSync('baiduToken',res.value)
				}catch(e){
					//TODO handle the exception
				}
			}
		})
		
	}
}